package com.xuhuan.practice.service.impl;

import com.xuhuan.practice.service.OSSService;
import com.xuhuan.practice.utils.MinioUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author: huan.xu
 * @create: 2024/6/12 10:51
 * @description: oss接口实现
 **/
@Service
public class OSSServiceImpl implements OSSService {

  /**
   * 上传文件
   *
   * @param file
   * @return
   */
  @Override
  public String upload(MultipartFile file) {
    return MinioUtil.putObject(file);
  }

  /**
   * 下载
   *
   * @param storagePath
   * @param request
   * @param response
   */
  @Override
  public void download(String storagePath, HttpServletRequest request,
      HttpServletResponse response) {
    InputStream inputStream = MinioUtil.getObject(storagePath);

    BufferedInputStream bis = null;
    BufferedOutputStream bos = null;
    OutputStream fos = null;

    try {
      bis = new BufferedInputStream(inputStream);
      fos = response.getOutputStream();
      bos = new BufferedOutputStream(fos);

      int byteRead = 0;
      byte[] buffer = new byte[8192];
      while ((byteRead = bis.read(buffer, 0, 8192)) != -1) {
        bos.write(buffer, 0, byteRead);
      }
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      try {
        bos.flush();
        bis.close();
        fos.close();
        bos.close();
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  }
}
